package com.ukao.cashregister.ui.clothinQuery;


import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.google.dexmaker.dx.rop.cst.CstArray;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.ClothingFactortAdapter;
import com.ukao.cashregister.adapter.ClothingManageAdapter;
import com.ukao.cashregister.adapter.ClothingStateAdapter;
import com.ukao.cashregister.adapter.OrderTagAdapter;
import com.ukao.cashregister.base.IAdapter;
import com.ukao.cashregister.base.IPage;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.base.PageWrapper;
import com.ukao.cashregister.bean.ClothIngManageBean;
import com.ukao.cashregister.bean.ClothginQuiryBean;
import com.ukao.cashregister.bean.ClothingFactoryBean;
import com.ukao.cashregister.bean.ClothingStateBean;
import com.ukao.cashregister.bean.MarkprintBean;
import com.ukao.cashregister.bean.OrderQuriyStateBean;
import com.ukao.cashregister.dialog.BindSignDialogFragment;
import com.ukao.cashregister.dialog.DialogTool;
import com.ukao.cashregister.eventbus.MembershipCardEvent;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.listener.MyTextWatcher;
import com.ukao.cashregister.listener.OnClickPopWindowListener;
import com.ukao.cashregister.listener.OnItemChildClickListener;
import com.ukao.cashregister.pesenter.ClothingManagePesenter;
import com.ukao.cashregister.printer.PrinterHelper;
import com.ukao.cashregister.ui.orderQuiry.OrderQuiryDetailFragment;
import com.ukao.cashregister.usbrfidreader.UsbrfidreaderHelper;
import com.ukao.cashregister.utils.CheckUsbDeviceUtils;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.DensityUtils;
import com.ukao.cashregister.utils.MyDateUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.ClothingManageView;
import com.ukao.cashregister.widget.ClearEditText;
import com.ukao.cashregister.widget.SpinnerPopWindow;
import com.ukao.cashregister.widget.StateButton;
import com.ukao.cashregister.widget.StateImageView;
import com.ukao.cashregister.widget.TwinklingLayout;

import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.cashregister.R.id.orderNo_layout;
import static com.ukao.cashregister.utils.MyDateUtils.getTime;


public class ClothingManageFragment extends MvpFragment<ClothingManagePesenter>  implements ClothingManageView{

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.fragment_arrive_shop_search1_edit)
    ClearEditText fragmentArriveShopSearch1Edit;
    @BindView(R.id.search_btn)
    Button searchBtn;
    @BindView(R.id.rfid_btn)
    StateImageView rfidBtn;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(R.id.start_time)
    StateButton startTime;
    @BindView(R.id.end_time)
    StateButton endTime;
    @BindView(R.id.pay_tage)
    TextView payTage;
    @BindView(R.id.pay_layout)
    RelativeLayout payLayout;
    @BindView(R.id.order_tage)
    TextView orderTage;
    @BindView(R.id.ordier_layout)
    RelativeLayout ordierLayout;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.twinkling_layout)
    TwinklingLayout twinklingLayout;
    Unbinder unbinder;
    @BindView(R.id.title)
    TextView title;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ClothingStateAdapter mClothingStateAdapter;
    private ClothingFactortAdapter mClothingFactortAdapter;

    private   String    timeType="yyyy/MM/dd";
    private List<OrderQuriyStateBean> mTimeData;
    private OrderTagAdapter mClothingTimeAdapter;
    private SpinnerPopWindow mTimePopWindow;
    private SpinnerPopWindow mfactoryPopWindow;
    private SpinnerPopWindow mstatePopWindow;
    public String factoryId="";
    public String proStatusVal="";
    private String[] timeStartDay;
    private int popupWindowWith;
    public String searchValue="";
    private PageWrapper mPageWrapper;
    private ClothingManageAdapter mClothingManageAdapter;
    private List<ClothIngManageBean.ListBean> mClothIngManageData;
    private boolean loadFinish;
    private boolean isSearch=true;  //是否搜索

    public static ClothingManageFragment newInstance(String param1, String param2) {
        ClothingManageFragment fragment = new ClothingManageFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected ClothingManagePesenter createPresenter() {
        return new ClothingManagePesenter(this);
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order_quiry, container, false);
        unbinder = ButterKnife.bind(this,view);
        initView();
        initListener();
        return view;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (!loadFinish)
        twinklingLayout.startRefresh();
    }

    @Override
    protected void initView() {
        UsbrfidreaderHelper.getInstance().readCardNum();
        rfidBtn.setVisibility(View.VISIBLE);
        fragmentArriveShopSearch1Edit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
        factoryId="";
        proStatusVal="";
        searchValue="";
        loadFinish=false;
        fragmentArriveShopSearch1Edit.setHint("衣物条码/手机号");
        title.setText("衣物管理");
        payTage.setText("所有工厂");
        orderTage.setText("所有衣物状态");
        fragmentArriveShopSearch1Edit.requestFocus();
        popupWindowWith = DensityUtils.getScreenW(activity) - DensityUtils.dip2px(_mActivity,90);
        initTimeData();
        initLinearRecyclerView(recyclerView);
        mClothIngManageData=new ArrayList<>();
         mClothingManageAdapter=new ClothingManageAdapter(_mActivity,mClothIngManageData);
        recyclerView.setAdapter(mClothingManageAdapter);
        IPage page = new IPage() {
            @Override
            public void load(int geIndex, int pageSize) {
                if (CheckUtils.isNull(startTime))return;
                String stratday = startTime.getText().toString();
                String endTimes = endTime.getText().toString();
                mvpPresenter.clothingProList( geIndex,pageSize,stratday,endTimes,factoryId ,proStatusVal,searchValue);

            }
        };
        mPageWrapper= new PageWrapper<>(mIAdapter, page);

    }


    @Override
    protected void initListener() {
        super.initListener();
        twinklingLayout.setOnRefreshListener(mRefreshListenerAdapter);
        mClothingManageAdapter.setOnItemClickListener(mOnItemClickListener);
        fragmentArriveShopSearch1Edit.addTextChangedListener(mTextWatcher);
        fragmentArriveShopSearch1Edit.setOnEditorActionListener(mOnEditorAction);
        mClothingManageAdapter.setOnItemChildClickListener(mOnItemChildClickListener);
        mTimePopWindow.setItemListener(mOnClickPopWindowListener);
    }


    private OnItemChildClickListener mOnItemChildClickListener=new OnItemChildClickListener() {


        @Override
        public void onChildItemClick(int id, int pos) {
          final   ClothIngManageBean.ListBean mitem = mClothingManageAdapter.getItem(pos);
                if (mitem==null)return;
            switch (id) {
                case R.id.orderNo_layout:
                    if (!CheckUtils.isEmpty(mitem.getOrderId()))
                        start(OrderQuiryDetailFragment.newInstance(mitem.getOrderId(),"衣物管理"),SINGLETASK);
                    break;
                case  R.id.marking_btn:/*打标和*/
                        mvpPresenter.printWash(_mActivity,mitem.getId()+"");
                    break;
                case R.id.bind_mark_btn: /*绑标*/
                    BindSignDialogFragment mBingSignDialog = BindSignDialogFragment.newInstance("","");
                    mBingSignDialog.setOnSureClickListener(message -> {
                        mvpPresenter.bindCode(mitem, (String)message);
                        isSearch=true;
                    });
                    isSearch=false;
                    mBingSignDialog.show(getChildFragmentManager(), BindSignDialogFragment.class.getName());
                    break;
            }
        }
    };
    TextView.OnEditorActionListener mOnEditorAction= (v, actionId, event) -> {
        if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {
                searchValueClothing();
        }
        return false;
    };

    private TextWatcher mTextWatcher=new MyTextWatcher(){

        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            searchValue=s.toString();
        }
    };


    private OnItemClickListener  mOnItemClickListener=new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            ClothIngManageBean.ListBean   mitem= (ClothIngManageBean.ListBean)o;

                mvpPresenter.clothginQuirydetail(_mActivity,mitem.getScanCode());
        }
    };

    private RefreshListenerAdapter mRefreshListenerAdapter = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(TwinklingRefreshLayout refreshLayout) {
            super.onRefresh(refreshLayout);
            mPageWrapper.loadPage(true);
        }

        @Override
        public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
            super.onLoadMore(refreshLayout);

            mPageWrapper.loadPage(false);

        }
    };


    IAdapter mIAdapter = new IAdapter() {
        @Override
        public void setDataSource(List data, boolean isNextLoad) {
            mClothingManageAdapter.setDatas(data);
            twinklingLayout.setEnableLoadmore(isNextLoad);
        }

        @Override
        public void loadMoreFinish(List data, boolean isNextLoad) {
            mClothingManageAdapter.addDatas(data);
            twinklingLayout.setEnableLoadmore(isNextLoad);

        }
    };

    @Override
    public void finishload() {
        twinklingLayout.finishRefreshing();
        twinklingLayout.finishLoadmore();
    }

    @Override
    public void clothingDetailsSuccess(ClothginQuiryBean mClothginQuiryBean ) {
        start(ClothingDetailsFragment.newInstance(mClothginQuiryBean),SINGLETASK);
    }

    @Override
    public void marKprintSucceed(MarkprintBean mMarkprintBean) {

        if(CheckUsbDeviceUtils.isWashprinter()){/*水洗*/
            PrinterHelper.getInstance().printWashing(mMarkprintBean);

        }
    }

    @Override
    public void bindMarkSucceed(ClothIngManageBean.ListBean item) {
        int index = mClothingManageAdapter.getDatas().indexOf(item);
        if (index!=-1){
            mClothingManageAdapter.notifyItemChanged(index);
        }
        isSearch=true;
    }


    private void initTimeData() {
        mTimeData = new ArrayList<>();
        timeStartDay=new  String[4];
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                "yyyy/MM/dd");
        long currentTime = System.currentTimeMillis();
        Date Enddate = new Date(currentTime);
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DAY_OF_MONTH, -30);
        String startThirtiTime = simpleDateFormat.format(now.getTime());
        Date StarSeventdate = new Date(currentTime - 7 * 24 * 60 * 60 * 1000);
        String endTimes= simpleDateFormat.format(Enddate);
        String startSevenTime = simpleDateFormat.format(StarSeventdate);
        timeStartDay[0]="";
        timeStartDay[1]=endTimes;
        timeStartDay[2]=startSevenTime;
        timeStartDay[3]=startThirtiTime;
        startTime.setText(startThirtiTime);
        endTime.setText(endTimes);
        String[] orderTime = resources.getStringArray(R.array.orderTime);
        //时间
        for(int i = 0; i < timeStartDay.length; i++) {
            if (i==0){
                mTimeData.add(new OrderQuriyStateBean(orderTime[i],timeStartDay[i],""));
            }else{
                mTimeData.add(new OrderQuriyStateBean(orderTime[i],timeStartDay[i],endTimes));
            }

        }

        /*时间*/
        mClothingTimeAdapter= new OrderTagAdapter(activity, mTimeData);
        mTimePopWindow= new SpinnerPopWindow(activity, "创建时间");
        mTimePopWindow.setAdapter(mClothingTimeAdapter,3);
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }
    @Subscribe
    public void onEvent(MembershipCardEvent event) {

        switch (event.getMessage()) {
            case add:/*成功*/
                if(isSearch){
                    String rfidSecretCard = (String) event.getData();
                    fragmentArriveShopSearch1Edit.setText(rfidSecretCard);
                    fragmentArriveShopSearch1Edit.setSelection(rfidSecretCard.length());
                    searchValueClothing();
                }
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        UsbrfidreaderHelper.getInstance().cancelReadCardNum();
        if (!CheckUtils.isNull(PrinterHelper.getInstance())) {
            PrinterHelper.getInstance().onDestroy();
        }
    }

    @OnClick({R.id.pay_layout, R.id.ordier_layout,R.id.search_btn,R.id.txt_time, R.id.start_time, R.id.end_time,R.id.rfid_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rfid_btn :
                UsbrfidreaderHelper.getInstance().readCardNum();
                break;

            case   R.id.search_btn:

                searchValueClothing();
            break;
            case R.id.pay_layout:
                if (CheckUtils.isNull(mClothingFactortAdapter)){
                    mvpPresenter.factorymerc();
                }else{
                    showfactoryPopWindow();
                }

                break;
            case R.id.ordier_layout:
                if (CheckUtils.isNull(mClothingStateAdapter)){
                    mvpPresenter.orderProductRel();
                }else{
                    showStatePopWindow();
                }

                break;
            case  R.id.txt_time:
                mTimePopWindow.setWidth(popupWindowWith);
                mTimePopWindow.showAsDropDown(txtTime);
                break;
            case   R.id.start_time :
                String birthday = startTime.getText().toString();

                DialogTool.getSingleton().showDatePicker(birthday,timeType,activity,mOnTimeSelectListener);
                break;
            case   R.id.end_time :

                String endTimes = endTime.getText().toString();
                DialogTool.getSingleton().showDatePicker(endTimes,timeType,activity,mEndSelectListener);

                break;

        }
    }

    private TimePickerView.OnTimeSelectListener mOnTimeSelectListener= new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {


            Date endData = MyDateUtils.stringDate(getText(endTime), timeType);

            if(endData==null){

            }else
            if ( date.getTime()>     endData.getTime()){
                T.show("开始时间不能大于结束时间");
                return;
            }
            startTime.setText(getTime(date,timeType));
            twinklingLayout.startRefresh();

        }
    };
    private TimePickerView.OnTimeSelectListener mEndSelectListener= new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            Date startData = MyDateUtils.stringDate(getText(startTime), timeType);
            if(startData==null){

            }else if (date.getTime()< startData.getTime()){
                T.show("结束时间不能小于开始时间");
                return;
            }
            endTime.setText(getTime(date,timeType));
            twinklingLayout.startRefresh();
        }
    };

    private void searchValueClothing() {
        searchValue=getText(fragmentArriveShopSearch1Edit);
        hideSoftInput();
        twinklingLayout.startRefresh();

    }

    @Override
    public void factorySucceed(List<ClothingFactoryBean> mData) {
        ClothingFactoryBean  mClothingFactoryBean=new ClothingFactoryBean("所有工厂","");
        mData.add(0,mClothingFactoryBean);
        mClothingFactortAdapter= new ClothingFactortAdapter(activity, mData);
        mfactoryPopWindow= new SpinnerPopWindow(activity, "工厂");
        mfactoryPopWindow.setAdapter(mClothingFactortAdapter,0);
        mfactoryPopWindow.setOnDismissListener(mFactoryListener);
        mfactoryPopWindow.setItemListener(mOnClickPopWindowListener);
        showfactoryPopWindow();

    }

    private void showfactoryPopWindow() {
        mfactoryPopWindow.setWidth(popupWindowWith);
        mfactoryPopWindow.showAsDropDown(payTage);
        if (mfactoryPopWindow.isShowing()) {
            payLayout.setBackgroundColor(getResource().getColor(R.color.line));
        }
    }

    @Override
    public void loadFail(String message) {
        T.show(message);
    }

    @Override
    public void clothingState(List<ClothingStateBean> mClothingState) {
        ClothingStateBean  mClothingStateBean=new ClothingStateBean("所有衣物状态","","");
        mClothingState.add(0,mClothingStateBean);
        mClothingStateAdapter= new ClothingStateAdapter(activity, mClothingState);
        mstatePopWindow= new SpinnerPopWindow(activity, "衣物状态");
        mstatePopWindow.setAdapter(mClothingStateAdapter,0);
        mstatePopWindow.setItemListener(mOnClickPopWindowListener);
        mstatePopWindow.setOnDismissListener(mstateListener);
        showStatePopWindow();

    }

    @Override
    public void clothIngTable(ClothIngManageBean mclothIngData) {
        mPageWrapper.addDataSource(mclothIngData.getList(),mclothIngData.getPages());
    }



    private PopupWindow.OnDismissListener mFactoryListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {

            payLayout.setBackgroundColor(getResource().getColor(R.color.pay_gay));


        }
    };

    private PopupWindow.OnDismissListener mstateListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {

            ordierLayout.setBackgroundColor(getResource().getColor(R.color.pay_gay));

        }
    };



    /**
     * 衣物状态
     */
    private void showStatePopWindow() {
        mstatePopWindow.setWidth(popupWindowWith);
        mstatePopWindow.showAsDropDown(ordierLayout);
        if (mstatePopWindow.isShowing()) {
            ordierLayout.setBackgroundColor(getResource().getColor(R.color.line));
        }
    }

    private OnClickPopWindowListener mOnClickPopWindowListener = new OnClickPopWindowListener() {




        @Override
        public void onSureItemClick(Object message) {


            if (!CheckUtils.isNull(mstatePopWindow)&&mstatePopWindow.isShowing()) {
                ClothingStateBean mClothingState = (ClothingStateBean) message;
                ordierLayout.setBackgroundColor(getResource().getColor(R.color.white));
                searchValue="";
                mstatePopWindow.dismiss();
                orderTage.setText(mClothingState.getText());
                proStatusVal = mClothingState.getVal();
                twinklingLayout.startRefresh();

            } else if (!CheckUtils.isNull(mfactoryPopWindow)&&mfactoryPopWindow.isShowing()) {
                ClothingFactoryBean mClothingFactory = (ClothingFactoryBean) message;
                payLayout.setBackgroundColor(getResource().getColor(R.color.white));
                searchValue="";
                mfactoryPopWindow.dismiss();
                payTage.setText(mClothingFactory.getName());
                factoryId = mClothingFactory.getId();
                twinklingLayout.startRefresh();


            } else if (mTimePopWindow.isShowing()) {
                OrderQuriyStateBean mOrderBean = (OrderQuriyStateBean) message;
                mTimePopWindow.dismiss();
                searchValue="";
                txtTime.setText(mOrderBean.getPayStatus());
                startTime.setText(mOrderBean.getStardtime());
                endTime.setText(mOrderBean.getEndtime());
                twinklingLayout.startRefresh();
            }
        }
    };


}
